package com.luoying.itew.activity;

import android.text.TextUtils;

import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;

import com.blankj.utilcode.util.NetworkUtils;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.luoying.itew.R;
import com.luoying.itew.bean.DistrictBean;
import com.luoying.itew.bean.MonitorBean;
import com.luoying.itew.bean.PointCityBean;
import com.luoying.itew.bean.StreetBean;
import com.luoying.itew.bean.UpdateRBean;
import com.luoying.itew.bean.UserInfo;
import com.luoying.itew.common.AntaiApplication;
import com.luoying.itew.db.DBManager;
import com.luoying.itew.http.BaseMap;
import com.luoying.itew.http.BaseResponse;
import com.luoying.itew.http.HttpRequestUtils;
import com.luoying.itew.http.rxjava.BaseHttpObserver;
import com.luoying.itew.http.rxjava.RxTransformerHelper;
import com.luoying.itew.manage.UserManage;
import com.luoying.itew.util.LogUtils;
import com.luoying.itew.util.StateContext;
import com.luoying.itew.util.ZXWUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.ObservableSource;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * Created by lufan on 2019-05-23
 * Class describe 主界面和上面Fragment公用的ViewModel
 * 就可以实现数据共享，不用耦合在Activity上面
 */
public class MainActivityViewModel extends ViewModel {

    private static final String TAG = "MainNewActivityViewModl";

    /**
     * 所有监测点数据
     */
    private MutableLiveData<List<MonitorBean>> allListMonitor = new MutableLiveData<>();

    /**
     * 所有街道办
     */
    private MutableLiveData<List<StreetBean>> allStree = new MutableLiveData<>();

    /**
     * 用户信息
     */
    private MutableLiveData<UserInfo> userInfo = new MutableLiveData<>();


    /**
     * 天气情况
     */
    private MutableLiveData<String> weather = new MutableLiveData<>();

    /**
     * 控制刷新
     */
    private MutableLiveData<Boolean> refresh = new MutableLiveData<>();

    /**
     * app更新信息
     */
    private MutableLiveData<UpdateRBean> updateBean = new MutableLiveData<>();


    public MutableLiveData<List<MonitorBean>> getAllListMonitor() {
        return allListMonitor;
    }

    public MutableLiveData<Boolean> getRefresh() {
        return refresh;
    }

    public MutableLiveData<List<StreetBean>> getAllStree() {
        return allStree;
    }

    public MutableLiveData<UserInfo> getUserInfo() {
        return userInfo;
    }

    public MutableLiveData<String> getWeather() {
        return weather;
    }

    public MutableLiveData<UpdateRBean> getUpdateBean() {
        return updateBean;
    }



    /**
     * 获取所有地图信息
     */
    public void getMapInfo(){
        if(!NetworkUtils.isConnected()){
            allListMonitor.setValue(sortList(UserManage.getInstance().getAllMonitorList()));
            refresh.setValue(false);
        } else {
            HttpRequestUtils.getInstance().getRxAppApi()
                    .userMapInfo(new BaseMap())
                    .compose(RxTransformerHelper.observableIO2Main())
                    .subscribe(new BaseHttpObserver<JsonObject>() {
                        @Override
                        protected void onSuccess(BaseResponse<JsonObject> baseResponse) {
                            refreshData(baseResponse.getResultEntity());
                        }

                        @Override
                        protected void onFailure(String errorMessage) {
                            LogUtils.e("onFailure:"+errorMessage);
                        }

                        @Override
                        protected void onRequestEnd() {
                            super.onRequestEnd();
                            refresh.setValue(false);
                        }
                    });
        }

    }

    /**
     * 获取个人信息并且获取所有监测点
     */
    public void getUserAndMapInfo(){
        HttpRequestUtils.getInstance().getRxAppApi().userInfo(new BaseMap())
                .flatMap((Function<BaseResponse<UserInfo>, ObservableSource<BaseResponse<JsonObject>>>) userResponse -> {
                    if(userResponse.isOk()){
                        UserManage.getInstance().saveUserInfo(userResponse.getResultEntity());
                        userInfo.postValue(userResponse.getResultEntity());
                        return HttpRequestUtils.getInstance().getRxAppApi().userMapInfo(new BaseMap());
                    } else {
                        return Observable.create(e -> e.onError(new Throwable(userResponse.getResultMessage())));
                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseHttpObserver<JsonObject>() {
                    @Override
                    protected void onSuccess(BaseResponse<JsonObject> baseResponse) {
                        refreshData(baseResponse.getResultEntity());
                    }

                    @Override
                    protected void onFailure(String errorMessage) {

                    }
                });
    }

    /**
     * 获取用户信息
     */
    public void getUserDetail(){
        //没有网络
        if(!NetworkUtils.isConnected()){
            Observable.create(new ObservableOnSubscribe<UserInfo>() {
                @Override
                public void subscribe(ObservableEmitter<UserInfo> emitter) throws Exception {
                    try {
                        UserInfo userInfo = DBManager.getInstance().getUser();
                        emitter.onNext(userInfo);
                        emitter.onComplete();
                    } catch (Exception e) {
                        e.printStackTrace();
                        emitter.onError(e);
                    }
                }
            }).subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Observer<UserInfo>() {
                @Override
                public void onSubscribe(Disposable d) {

                }

                @Override
                public void onNext(UserInfo info) {
                    userInfo.setValue(info);
                }

                @Override
                public void onError(Throwable e) {

                }

                @Override
                public void onComplete() {
                }
            });

        } else {
            HttpRequestUtils.getInstance().getRxAppApi().userInfo(new BaseMap())
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new BaseHttpObserver<UserInfo>() {
                        @Override
                        protected void onSuccess(BaseResponse<UserInfo> baseResponse) {
                            userInfo.setValue(baseResponse.getResultEntity());
                        }

                        @Override
                        protected void onFailure(String errorMessage) {

                        }
                    });
        }

    }

    /**
     * 获取天气情况
     */
    public void getWeatherInfo(){
        HttpRequestUtils.getInstance().getRxAppApi()
                .getWeatherInfo(new BaseMap())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseHttpObserver<JsonObject>() {
                    @Override
                    protected void onSuccess(BaseResponse<JsonObject> baseResponse) {
                        String weathertype = "";
                        String wendu = "";
                        try {
                            JsonObject weatherJson = baseResponse.getResultEntity().getAsJsonObject("cityWeather");
                            wendu = weatherJson.get("wendu").getAsString();
                            JsonArray jsonArray = weatherJson.getAsJsonArray("forecast");
                            if(jsonArray!=null&&jsonArray.size()!=0){
                                weathertype = jsonArray.get(0).getAsJsonObject().get("day").getAsJsonObject().get("type").getAsString();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        if(TextUtils.isEmpty(weathertype)||TextUtils.isEmpty(wendu)){
                            weather.setValue("");
                        }
                        String string = String.format(AntaiApplication.context.getString(R.string.weather_info), weathertype, wendu);
                        weather.setValue(string);
                    }

                    @Override
                    protected void onFailure(String errorMessage) {
                        weather.setValue("");
                    }
                });
    }

    /**
     * 退出登录
     */
    public void logout(int type){
        UserInfo userInfo = UserManage.getInstance().getUserInfo();
        BaseMap baseMap = new BaseMap();
//                .put("userId",userInfo==null?"0":userInfo.getUserId())
//                .put("flag",type);
        HttpRequestUtils.getInstance().getRxAppApi()
                .breakApp(baseMap,userInfo==null?0:userInfo.getUserId(),type)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseHttpObserver<String>() {
                    @Override
                    protected void onSuccess(BaseResponse<String> baseResponse) {
                        LogUtils.d("logout success");
                    }

                    @Override
                    protected void onFailure(String errorMessage) {
                        LogUtils.d("logout failure:"+errorMessage);
                    }
                });
    }

    /**
     * 极光推送数据绑定
     */
    public void jigrangBind(){
        HttpRequestUtils.getInstance().getRxAppApi()
                .jiguangBind(new BaseMap())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseHttpObserver<String>() {
                    @Override
                    protected void onSuccess(BaseResponse<String> baseResponse) {
                        LogUtils.d("极光绑定成功");
                    }

                    @Override
                    protected void onFailure(String errorMessage) {
                        LogUtils.d("极光绑定失败："+errorMessage);
                    }
                });
    }

    /**
     * 刷新数据
     * @param data
     */
    private void refreshData(JsonObject data ){
        Gson gson = new Gson();
        UserManage.getInstance().saveUserCity(gson.fromJson(data.get("userCity"), PointCityBean.class));

        //处理监测点数据
        List<DistrictBean> listdDstrict =gson.fromJson(data.get("districtJson"),new TypeToken<List<DistrictBean>>(){}.getType());
        UserManage.getInstance().setMonitorBeanList(listdDstrict);
        List<MonitorBean> list = new ArrayList<>();
        for (DistrictBean districtBean : listdDstrict) {
            for (MonitorBean bean : districtBean.getMonitorPoints()) {
                //过滤掉未上线的数据
                if(bean.getMonitorStatus()==1){
                    list.add(bean);
                }
            }
        }
        //存检测点数据
        UserManage.getInstance().saveMonitorList(list);

        List<MonitorBean> allList = new ArrayList<>(UserManage.getInstance().getAllMonitorList());
        //监测点预警级别排序
        allListMonitor.setValue(sortList(allList));
        //处理街道办数据
        //保存所有街道
        List<StreetBean> jsonStree = gson.fromJson(data.get("region"), new TypeToken<List<StreetBean>>() {}.getType());
        UserManage.getInstance().saveAllStreet(jsonStree);
        allStree.setValue(jsonStree);

    }

    /**
     * 对对数组排序
     */
    private List<MonitorBean> sortList(List<MonitorBean> list){
        Collections.sort(list, (o1, o2) -> {
            StateContext context1 = new StateContext(o1.getMonitorPointStatus(),o1.getWarnCoefficient());
            StateContext context2 = new StateContext(o2.getMonitorPointStatus(),o2.getWarnCoefficient());
            return Integer.compare(context2.stateLeve(),context1.stateLeve());
        });
        return  list;
    }

    /**
     * 获取更新更新
     */
    public void updateVersion(){
        BaseMap baseMap = new BaseMap();
        baseMap.put("appVersion","antai_"+ ZXWUtils.packageName(AntaiApplication.context));
        baseMap.put("appUogradeNo",ZXWUtils.packageCode(AntaiApplication.context));
        baseMap.put("fromAppClient","android");
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"),new Gson().toJson(baseMap));
        HttpRequestUtils.getInstance().getRxAppApi()
                .update(body)
                .compose(RxTransformerHelper.observableIO2Main())
                .subscribe(new BaseHttpObserver<UpdateRBean>() {
                    @Override
                    protected void onSuccess(BaseResponse<UpdateRBean> baseResponse) {
                        LogUtils.d(TAG,"update---:"+baseResponse.getResultEntity().isIsUpgrade());
                        updateBean.setValue(baseResponse.getResultEntity());
                    }

                    @Override
                    protected void onFailure(String errorMessage) {
                        LogUtils.d(TAG,"update---:"+errorMessage);
                        updateBean.setValue(null);
                    }
                });

    }

}
